# -*-coding=utf-8-*-
# 知乎热榜推送工具 - 包含UI界面和核心功能
# By:咸鱼网友

import tkinter as tk
from tkinter import ttk, messagebox
import smtplib
import time
import requests
import os
import re
import sys
import json
import webbrowser
import urllib3
from email.mime.text import MIMEText
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from pyquery import PyQuery
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


class SettingsWindow:
    def __init__(self, parent):
        self.parent = parent
        self.window = tk.Toplevel(parent.root)
        self.window.title("设置")
        self.window.geometry("400x400")
        self.window.resizable(False, False)
        self.window.withdraw()  # 初始隐藏窗口
        
        # 居中显示窗口
        self.center_window()
        
        # 创建设置界面
        self.create_widgets()
        
        # 加载现有配置
        self.load_settings()
        
        # 显示窗口
        self.window.deiconify()
        
    def center_window(self):
        """将窗口居中显示"""
        self.window.update_idletasks()
        width = 400
        height = 400
        x = (self.window.winfo_screenwidth() // 2) - (width // 2)
        y = (self.window.winfo_screenheight() // 2) - (height // 2)
        self.window.geometry(f'{width}x{height}+{x}+{y}')
        
    def create_widgets(self):
        """创建设置界面组件"""
        # 创建主框架
        main_frame = ttk.Frame(self.window, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建笔记本控件（选项卡）
        notebook = ttk.Notebook(main_frame)
        notebook.pack(fill=tk.BOTH, expand=True)
        
        # SMTP设置选项卡
        smtp_frame = ttk.Frame(notebook)
        notebook.add(smtp_frame, text="SMTP设置")
        self.create_smtp_settings(smtp_frame)
        
        # 知乎设置选项卡
        zhihu_frame = ttk.Frame(notebook)
        notebook.add(zhihu_frame, text="知乎设置")
        self.create_zhihu_settings(zhihu_frame)
        
        # 定时任务选项卡
        schedule_frame = ttk.Frame(notebook)
        notebook.add(schedule_frame, text="定时任务")
        self.create_schedule_settings(schedule_frame)
        
        # 开机启动选项卡
        startup_frame = ttk.Frame(notebook)
        notebook.add(startup_frame, text="开机启动")
        self.create_startup_settings(startup_frame)
        
        # 确定和取消按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(10, 0))
        
        ttk.Button(button_frame, text="确定", command=self.save_settings).pack(side=tk.RIGHT, padx=(5, 0))
        ttk.Button(button_frame, text="取消", command=self.window.destroy).pack(side=tk.RIGHT)
        
    def create_smtp_settings(self, parent):
        """创建SMTP设置界面"""
        # SMTP服务器设置
        ttk.Label(parent, text="SMTP服务器设置", font=("微软雅黑", 10, "bold")).pack(anchor=tk.W, pady=(0, 10))
        
        # 用户名
        username_frame = ttk.Frame(parent)
        username_frame.pack(fill=tk.X, pady=5)
        ttk.Label(username_frame, text="用户名:").pack(side=tk.LEFT)
        self.smtp_username_var = tk.StringVar()
        ttk.Entry(username_frame, textvariable=self.smtp_username_var).pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=(10, 0))
        
        # 密码
        password_frame = ttk.Frame(parent)
        password_frame.pack(fill=tk.X, pady=5)
        ttk.Label(password_frame, text="密码:").pack(side=tk.LEFT)
        self.smtp_password_var = tk.StringVar()
        password_entry = ttk.Entry(password_frame, textvariable=self.smtp_password_var, show="*")
        password_entry.pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=(10, 0))
        
        # 服务器地址
        server_frame = ttk.Frame(parent)
        server_frame.pack(fill=tk.X, pady=5)
        ttk.Label(server_frame, text="服务器:").pack(side=tk.LEFT)
        self.smtp_server_var = tk.StringVar()
        ttk.Entry(server_frame, textvariable=self.smtp_server_var).pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=(10, 0))
        
        # 端口
        port_frame = ttk.Frame(parent)
        port_frame.pack(fill=tk.X, pady=5)
        ttk.Label(port_frame, text="端口:").pack(side=tk.LEFT)
        self.smtp_port_var = tk.StringVar()
        ttk.Entry(port_frame, textvariable=self.smtp_port_var, width=10).pack(side=tk.RIGHT, padx=(10, 0))
        
    def create_zhihu_settings(self, parent):
        """创建知乎设置界面"""
        # 知乎Cookie设置
        ttk.Label(parent, text="知乎Cookie设置", font=("微软雅黑", 10, "bold")).pack(anchor=tk.W, pady=(0, 10))
        
        # Cookie输入框
        cookie_frame = ttk.Frame(parent)
        cookie_frame.pack(fill=tk.X, pady=5)
        ttk.Label(cookie_frame, text="Cookie:").pack(side=tk.LEFT)
        self.zhihu_cookie_var = tk.StringVar()
        ttk.Entry(cookie_frame, textvariable=self.zhihu_cookie_var).pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=(10, 0))
        
        # 获取Cookie帮助
        help_frame = ttk.Frame(parent)
        help_frame.pack(fill=tk.X, pady=(20, 0))
        ttk.Label(help_frame, text="如何获取知乎Cookie:", font=("微软雅黑", 9, "bold")).pack(anchor=tk.W)
        ttk.Label(help_frame, text="1. 登录知乎网站", font=("微软雅黑", 9)).pack(anchor=tk.W)
        ttk.Label(help_frame, text="2. 按F12打开开发者工具", font=("微软雅黑", 9)).pack(anchor=tk.W)
        ttk.Label(help_frame, text="3. 刷新页面，在Network标签中找到请求", font=("微软雅黑", 9)).pack(anchor=tk.W)
        ttk.Label(help_frame, text="4. 在请求头中找到Cookie并复制", font=("微软雅黑", 9)).pack(anchor=tk.W)
        
        # 获取Cookie按钮
        ttk.Button(parent, text="打开知乎登录页面", command=self.open_zhihu).pack(pady=(10, 0))
        
    def create_schedule_settings(self, parent):
        """创建定时任务设置界面"""
        ttk.Label(parent, text="定时运行设置", font=("微软雅黑", 10, "bold")).pack(anchor=tk.W, pady=(0, 10))
        
        # 定时运行开关
        schedule_frame = ttk.Frame(parent)
        schedule_frame.pack(fill=tk.X, pady=5)
        self.schedule_enabled_var = tk.BooleanVar()
        ttk.Checkbutton(schedule_frame, text="启用定时运行", variable=self.schedule_enabled_var).pack(side=tk.LEFT)
        
        # 运行时间设置
        time_frame = ttk.Frame(parent)
        time_frame.pack(fill=tk.X, pady=5)
        ttk.Label(time_frame, text="运行时间:").pack(side=tk.LEFT)
        self.schedule_time_var = tk.StringVar(value="09:00")
        ttk.Entry(time_frame, textvariable=self.schedule_time_var, width=10).pack(side=tk.LEFT, padx=(10, 0))
        ttk.Label(time_frame, text="(格式: HH:MM)").pack(side=tk.LEFT, padx=(5, 0))
        
        # 运行频率
        frequency_frame = ttk.Frame(parent)
        frequency_frame.pack(fill=tk.X, pady=5)
        ttk.Label(frequency_frame, text="运行频率:").pack(side=tk.LEFT)
        self.schedule_frequency_var = tk.StringVar(value="每天")
        frequency_combo = ttk.Combobox(frequency_frame, textvariable=self.schedule_frequency_var, 
                                      values=["每天", "每周一", "每周五"], state="readonly", width=10)
        frequency_combo.pack(side=tk.LEFT, padx=(10, 0))
        
    def create_startup_settings(self, parent):
        """创建开机启动设置界面"""
        ttk.Label(parent, text="开机启动设置", font=("微软雅黑", 10, "bold")).pack(anchor=tk.W, pady=(0, 10))
        
        # 开机启动开关
        startup_frame = ttk.Frame(parent)
        startup_frame.pack(fill=tk.X, pady=5)
        self.startup_enabled_var = tk.BooleanVar()
        ttk.Checkbutton(startup_frame, text="开机自动启动", variable=self.startup_enabled_var).pack(side=tk.LEFT)
        
        # 启动参数设置
        args_frame = ttk.Frame(parent)
        args_frame.pack(fill=tk.X, pady=(20, 0))
        ttk.Label(args_frame, text="启动参数:", font=("微软雅黑", 9, "bold")).pack(anchor=tk.W)
        
        # 邮箱地址
        email_frame = ttk.Frame(parent)
        email_frame.pack(fill=tk.X, pady=5)
        ttk.Label(email_frame, text="邮箱:").pack(side=tk.LEFT)
        self.startup_email_var = tk.StringVar()
        ttk.Entry(email_frame, textvariable=self.startup_email_var).pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=(10, 0))
        
        # 热榜条数
        count_frame = ttk.Frame(parent)
        count_frame.pack(fill=tk.X, pady=5)
        ttk.Label(count_frame, text="条数:").pack(side=tk.LEFT)
        self.startup_count_var = tk.StringVar(value="10")
        ttk.Entry(count_frame, textvariable=self.startup_count_var, width=10).pack(side=tk.RIGHT, padx=(10, 0))
        
    def open_zhihu(self):
        """打开知乎登录页面"""
        try:
            webbrowser.open("https://www.zhihu.com/signin")
        except Exception as e:
            messagebox.showerror("错误", f"无法打开浏览器: {e}")
            
    def load_settings(self):
        """加载现有设置"""
        # 加载所有设置
        if os.path.exists("config.json"):
            try:
                with open("config.json", "r", encoding="utf-8") as f:
                    config = json.load(f)
                    
                # 加载SMTP设置
                if "smtp" in config:
                    smtp_config = config["smtp"]
                    self.smtp_username_var.set(smtp_config.get("username", ""))
                    self.smtp_password_var.set(smtp_config.get("password", ""))
                    self.smtp_server_var.set(smtp_config.get("server", ""))
                    self.smtp_port_var.set(smtp_config.get("port", ""))
                    
                # 加载知乎Cookie设置
                if "zhihu" in config:
                    zhihu_config = config["zhihu"]
                    self.zhihu_cookie_var.set(zhihu_config.get("cookie", ""))
                    
                # 加载定时任务设置
                if "schedule" in config:
                    schedule_config = config["schedule"]
                    self.schedule_enabled_var.set(schedule_config.get("enabled", False))
                    self.schedule_time_var.set(schedule_config.get("time", "09:00"))
                    self.schedule_frequency_var.set(schedule_config.get("frequency", "每天"))
                    
                # 加载开机启动设置
                if "startup" in config:
                    startup_config = config["startup"]
                    self.startup_enabled_var.set(startup_config.get("enabled", False))
                    self.startup_email_var.set(startup_config.get("email", ""))
                    self.startup_count_var.set(startup_config.get("count", "10"))
                    
            except Exception as e:
                print(f"加载配置时出错: {e}")
        else:
            # 如果配置文件不存在，显示填写样例
            self.smtp_username_var.set("example@qq.com")
            self.smtp_password_var.set("your_password_or_auth_code")
            self.smtp_server_var.set("smtp.qq.com")
            self.smtp_port_var.set("465")
            self.zhihu_cookie_var.set("your_zhihu_cookie")
            self.startup_email_var.set("recipient@example.com")
            self.startup_count_var.set("10")
        
    def save_settings(self):
        """保存设置"""
        try:
            # 构建配置字典
            config = {
                "smtp": {
                    "username": self.smtp_username_var.get(),
                    "password": self.smtp_password_var.get(),
                    "server": self.smtp_server_var.get(),
                    "port": self.smtp_port_var.get()
                },
                "zhihu": {
                    "cookie": self.zhihu_cookie_var.get()
                },
                "schedule": {
                    "enabled": self.schedule_enabled_var.get(),
                    "time": self.schedule_time_var.get(),
                    "frequency": self.schedule_frequency_var.get()
                },
                "startup": {
                    "enabled": self.startup_enabled_var.get(),
                    "email": self.startup_email_var.get(),
                    "count": self.startup_count_var.get()
                }
            }
            
            # 保存到JSON文件
            with open("config.json", "w", encoding="utf-8") as f:
                json.dump(config, f, ensure_ascii=False, indent=4)
                
            messagebox.showinfo("成功", "设置已保存")
            self.window.destroy()
        except Exception as e:
            messagebox.showerror("错误", f"保存设置时出错: {e}")


class ZhihuHotlistSender:
    def __init__(self):
        self.root = tk.Tk()
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI界面"""
        # 创建主窗口
        self.root.title("知乎热榜推送工具")
        
        # 设置窗口尺寸并居中显示
        window_width = 270
        window_height = 140
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")
        
        self.root.resizable(False, False)

        # 设置样式
        style = ttk.Style()
        style.configure("TLabel", font=("微软雅黑", 10))
        style.configure("TButton", font=("微软雅黑", 10))
        style.configure("TEntry", font=("微软雅黑", 10))

        # 创建主框架
        main_frame = ttk.Frame(self.root)
        main_frame.pack(expand=True, fill=tk.BOTH)

        # 创建容器框架，用于居中对齐
        container_frame = ttk.Frame(main_frame)
        container_frame.pack(expand=True, fill=tk.BOTH)

        # 第一行：邮箱输入（居中）
        email_frame = ttk.Frame(container_frame)
        email_frame.pack(fill=tk.X, pady=5)
        
        email_label = ttk.Label(email_frame, text="接收邮箱:")
        email_label.pack(side=tk.LEFT, padx=(20, 5))
        
        self.email_var = tk.StringVar()
        email_entry = ttk.Entry(email_frame, textvariable=self.email_var)
        email_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 20))

        # 第二行：热榜条数输入（居中）
        count_frame = ttk.Frame(container_frame)
        count_frame.pack(fill=tk.X, pady=5)
        
        count_label = ttk.Label(count_frame, text="热榜条数:")
        count_label.pack(side=tk.LEFT, padx=(20, 5))
        
        self.count_var = tk.StringVar(value="10")  # 默认值为10
        count_entry = ttk.Entry(count_frame, textvariable=self.count_var, width=10)
        count_entry.pack(side=tk.LEFT, padx=(5, 20))

        # 第三行：发送按钮（居中）和设置按钮（靠右）
        button_frame = ttk.Frame(container_frame)
        button_frame.pack(fill=tk.X, pady=10)
        
        # 左侧留空
        left_spacer = ttk.Frame(button_frame)
        left_spacer.pack(side=tk.LEFT, expand=True)
        
        # 发送按钮（居中）
        send_button = ttk.Button(button_frame, text="发送热榜到邮箱", command=self.send_button_clicked)
        send_button.pack(side=tk.LEFT)
        
        # 右侧留空
        right_spacer = ttk.Frame(button_frame)
        right_spacer.pack(side=tk.LEFT, expand=True)
        
        # 设置按钮（靠右）
        settings_button = ttk.Button(button_frame, text="⚙", command=self.settings_button_clicked, width=3)
        settings_button.pack(side=tk.RIGHT, padx=(0, 20))
        
        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)

        # 如果setting.txt存在，读取现有配置
        self.load_existing_config()
        
    def update_status(self, message):
        """更新状态栏显示"""
        self.status_var.set(message)
        self.root.update_idletasks()  # 立即更新界面
        
    def load_existing_config(self):
        """加载现有配置"""
        # 优先加载JSON配置文件
        if os.path.exists("config.json"):
            try:
                with open("config.json", "r", encoding="utf-8") as f:
                    config = json.load(f)
                    
                # 读取启动参数
                if "startup" in config:
                    startup_config = config["startup"]
                    self.email_var.set(startup_config.get("email", ""))
                    self.count_var.set(startup_config.get("count", "10"))
                return
            except Exception as e:
                self.update_status(f"读取配置文件时出错: {e}")
                
        # 如果没有JSON配置文件，尝试读取旧的setting.txt
        if os.path.exists("setting.txt"):
            try:
                with open("setting.txt", "r", encoding="utf-8") as f:
                    lines = f.readlines()
                    if len(lines) >= 4:
                        # 读取邮箱地址
                        self.email_var.set(lines[1].strip())
                        # 读取热榜条数
                        self.count_var.set(lines[3].strip())
            except Exception as e:
                self.update_status(f"读取配置文件时出错: {e}")
        else:
            # 如果配置文件都不存在，显示填写样例
            self.email_var.set("recipient@example.com")
            self.count_var.set("10")
                
    def validate_inputs(self):
        """验证用户输入"""
        email = self.email_var.get().strip()
        count = self.count_var.get().strip()
        
        # 验证邮箱格式
        if not email:
            self.update_status("错误: 请输入接收邮箱地址")
            return False
            
        if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
            self.update_status("错误: 邮箱格式不正确")
            return False
            
        # 验证热榜条数
        if not count:
            self.update_status("错误: 请输入热榜条数")
            return False
            
        try:
            count_num = int(count)
            if count_num <= 0 or count_num > 50:
                self.update_status("错误: 热榜条数必须在1-50之间")
                return False
        except ValueError:
            self.update_status("错误: 热榜条数必须是数字")
            return False
            
        return True, email, int(count)
        
    def save_config(self, email, count):
        """保存配置到文件"""
        try:
            # 更新JSON配置文件中的启动参数
            config = {}
            if os.path.exists("config.json"):
                try:
                    with open("config.json", "r", encoding="utf-8") as f:
                        config = json.load(f)
                except:
                    pass
                    
            # 更新启动参数
            if "startup" not in config:
                config["startup"] = {}
            config["startup"]["email"] = email
            config["startup"]["count"] = str(count)
            
            # 保存到JSON文件
            with open("config.json", "w", encoding="utf-8") as f:
                json.dump(config, f, ensure_ascii=False, indent=4)
                
            return True
        except Exception as e:
            self.update_status(f"保存配置时出现错误: {e}")
            return False
            
    def send_button_clicked(self):
        """发送按钮点击事件"""
        # 验证输入
        validation_result = self.validate_inputs()
        if not validation_result[0]:
            return
            
        email, count = validation_result[1], validation_result[2]
        
        # 保存配置
        if not self.save_config(email, count):
            return
        
        # 显示成功消息
        self.update_status("配置已保存，即将开始发送热榜...")
        
        # 禁用发送按钮防止重复点击
        self.set_send_button_state(tk.DISABLED)
        
        # 使用after方法在主线程中执行发送任务，避免阻塞UI
        self.root.after(100, self.execute_sendmail, count)
        
    def execute_sendmail(self, count):
        """在主线程中执行发送邮件任务"""
        try:
            self.sendmail(count)
            self.update_status("热榜已成功发送到您的邮箱！")
        except Exception as e:
            self.update_status(f"发送过程中出现错误: {e}")
        finally:
            # 重新启用发送按钮
            self.set_send_button_state(tk.NORMAL)
            
    def set_send_button_state(self, state):
        """设置发送按钮状态"""
        # 遍历所有子组件找到发送按钮并设置状态
        for widget in self.root.winfo_children():
            for subwidget in widget.winfo_children():
                if isinstance(subwidget, ttk.Frame):
                    for button in subwidget.winfo_children():
                        if isinstance(button, ttk.Button) and button.cget("text") == "发送热榜到邮箱":
                            button.config(state=state)
        
    def settings_button_clicked(self):
        """设置按钮点击事件"""
        # 打开设置窗口
        SettingsWindow(self)
            
    '''获取热榜内容，并返回标题title、简介content、链接link'''
    def getinfo(self):  # 获取热榜内容
        """获取热榜内容"""
        url = "https://www.zhihu.com/hot"
        
        # 检查环境变量中是否有cookie配置
        cookie_str = os.environ.get('ZHIHU_COOKIE', None)
        if cookie_str:
            Mycookie = {"cookie": cookie_str}
        else:
            # 检查是否保存了cookie配置
            if os.path.exists("config.json"):
                try:
                    with open("config.json", "r", encoding="utf-8") as f:
                        config = json.load(f)
                        if "zhihu" in config:
                            cookie_str = config["zhihu"].get("cookie", "")
                            if cookie_str:
                                Mycookie = {"cookie": cookie_str}
                            else:
                                Mycookie = {"cookie": "*"}  # 空cookie占位符
                        else:
                            Mycookie = {"cookie": "*"}  # 空cookie占位符
                except Exception:
                    Mycookie = {"cookie": "*"}  # 空cookie占位符
            else:
                Mycookie = {"cookie": "*"}  # 空cookie占位符
        
        # 首先尝试使用requests获取
        try:
            r = requests.get(url, headers={"user-agent": UserAgent().random}, cookies=Mycookie, timeout=30)
            r.encoding = r.apparent_encoding
            r.raise_for_status()  # 如果连接失败，弹出报错
            
            # 分析网页
            soup = BeautifulSoup(r.text, "html.parser")
            HotLists = soup.find_all("section")  # 提取热榜模块
            
            # 如果能成功获取到内容，使用传统方法
            if HotLists:
                self.update_status("成功访问知乎热榜！")
                return self._parse_hotlist_with_bs4(HotLists)
        except requests.RequestException as e:
            self.update_status(f"访问知乎热榜失败: {e}")
        
        # 如果requests方法失败，尝试使用Selenium
        self.update_status("尝试使用浏览器自动化获取...")
        return self._get_hotlist_with_selenium()
    
    def _parse_hotlist_with_bs4(self, hotlists):
        """使用BeautifulSoup解析热榜"""
        title, content, link = [], [], []  # 定义内容列表
        
        for hotnews in hotlists:
            # 获取标题
            try:
                title.append(hotnews.h2.get_text().strip())
            except AttributeError:
                title.append("无标题")
            
            # 获取内容
            try:
                content_text = hotnews.p.get_text().strip() if hotnews.p else ""
                content.append(content_text)
            except AttributeError:
                content.append("")
            
            # 获取链接
            try:
                href = hotnews.a["href"]
                # 处理相对链接
                if href.startswith("/"):
                    href = "https://www.zhihu.com" + href
                link.append(href)
            except (AttributeError, KeyError):
                link.append("")

        self.update_status("热榜分析完成，已提取内容")
        return title, content, link
    
    def _get_hotlist_with_selenium(self):
        """使用Selenium获取热榜内容"""
        # 检查是否有已存在的驱动
        driver_path = None
        
        # 首先检查本地是否已有驱动
        local_driver = "msedgedriver.exe"
        if os.path.exists(local_driver):
            driver_path = local_driver
            self.update_status("使用本地浏览器驱动...")
        else:
            # 尝试使用webdriver-manager自动管理驱动
            try:
                self.update_status("检查浏览器驱动...")
                from webdriver_manager.microsoft import EdgeChromiumDriverManager
                from webdriver_manager.core.driver_cache import DriverCacheManager
                
                # 使用自定义缓存管理器
                cache_manager = DriverCacheManager()
                driver_path = EdgeChromiumDriverManager(cache_manager=cache_manager).install()
                self.update_status("浏览器驱动已准备...")
            except Exception as e:
                self.update_status(f"下载驱动失败: {e}")
                return [], [], []
        
        # 设置Edge浏览器选项
        edge_options = EdgeOptions()
        edge_options.add_argument('--headless')  # 无头模式
        edge_options.add_argument('--no-sandbox')
        edge_options.add_argument('--disable-dev-shm-usage')
        edge_options.add_argument('--disable-gpu')
        edge_options.add_argument('--window-size=1920,1080')
        edge_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
        
        driver = None
        try:
            if driver_path:
                driver = webdriver.Edge(executable_path=driver_path, options=edge_options)
            else:
                # 尝试默认路径
                driver = webdriver.Edge(options=edge_options)
                
            self.update_status("正在访问知乎热榜页面...")
            driver.get("https://www.zhihu.com/hot")
            
            # 等待页面加载完成
            wait = WebDriverWait(driver, 30)
            
            # 等待热榜元素出现
            self.update_status("等待页面加载...")
            wait.until(EC.presence_of_element_located((By.TAG_NAME, "section")))
            
            # 给页面一些时间加载动态内容
            time.sleep(5)
            
            self.update_status("页面加载完成，开始解析内容...")
            
            # 查找热榜条目
            hot_items = driver.find_elements(By.CSS_SELECTOR, "section")
            self.update_status(f"找到 {len(hot_items)} 个热榜条目")
            
            titles = []
            contents = []
            links = []
            
            # 解析热榜条目
            for i, item in enumerate(hot_items):
                try:
                    # 获取标题
                    title_element = item.find_element(By.CSS_SELECTOR, "h2")
                    title = title_element.text.strip()
                    titles.append(title)
                    
                    # 获取内容摘要
                    try:
                        content_element = item.find_element(By.CSS_SELECTOR, "p")
                        content = content_element.text.strip()
                    except:
                        content = ""
                    contents.append(content)
                    
                    # 获取链接
                    try:
                        link_element = item.find_element(By.CSS_SELECTOR, "a")
                        link = link_element.get_attribute("href")
                        # 处理相对链接
                        if link.startswith("/"):
                            link = "https://www.zhihu.com" + link
                    except:
                        link = ""
                    links.append(link)
                    
                except Exception as e:
                    print(f"解析第{i+1}个条目时出错: {e}")
                    titles.append("无标题")
                    contents.append("")
                    links.append("")
            
            self.update_status("热榜分析完成，已提取内容")
            return titles, contents, links
            
        except Exception as e:
            self.update_status(f"浏览器自动化获取失败: {e}")
            return [], [], []
            
        finally:
            if driver:
                driver.quit()
        
    def getname(self, num):
        now = time.strftime("【%Y年%m月%d日 %H:%M】", time.localtime())
        filename = "知乎热榜" + "TOP" + str(num) + now
        return filename

    '''生成网页并返回html文本'''
    def gethtml(self, num):
        self.update_status("正在生成HTML内容...")
        html = PyQuery(filename="index.html", encoding="UTF-8")
        title, content, link = self.getinfo()
        html("header h1").text(self.getname(num))  # 添加标题
        article = html("body")  # 添加内容
        
        # 确保num不超过实际获取到的热榜条目数
        actual_num = min(num, len(title))
        
        for i in range(actual_num):
            h3 = '<article><h3 class="title">%s</h3><hr size="1px" color="#8b8b8b">' % f"TOP{i+1}:{title[i]}"
            p = '<p class="content">%s</p>' % content[i]
            a = '<a href="%s" target="_blank" class="link">查看知乎讨论</a></article>' % link[i]
            article.append("{}{}{}".format(h3, p, a))
        
        self.update_status("内容已填充至网页，html文本生成成功！")
        return html

    '''发送文件至邮箱,括号内参数为新闻条数'''
    def sendmail(self, num):
        html = str(self.gethtml(num))  # 获取待发送主体内容
        title = self.getname(num)  # 获取邮件标题
        
        # 读取配置文件
        try:
            with open("setting.txt", "r", encoding="utf-8") as f:
                lines = f.readlines()
            receiver = lines[1].strip()  # 读取收件人地址
        except FileNotFoundError:
            self.update_status("未找到配置文件 setting.txt，请创建该文件并配置收件人信息")
            return
        except IndexError:
            self.update_status("配置文件格式不正确，请检查 setting.txt")
            return
        
        '''初始化邮箱'''
        self.update_status("邮箱初始化...")
        
        # 检查环境变量中是否有邮箱配置
        smtp_config = None
        if all(key in os.environ for key in ['SMTP_USERNAME', 'SMTP_PASSWORD', 'SMTP_HOST', 'SMTP_PORT']):
            smtp_config = [
                os.environ['SMTP_USERNAME'],
                os.environ['SMTP_PASSWORD'],
                os.environ['SMTP_HOST'],
                os.environ['SMTP_PORT']
            ]
        # 检查是否保存了SMTP配置
        elif os.path.exists("config.json"):
            try:
                with open("config.json", "r", encoding="utf-8") as f:
                    config = json.load(f)
                    if "smtp" in config:
                        smtp_settings = config["smtp"]
                        smtp_config = [
                            smtp_settings.get("username", ""),
                            smtp_settings.get("password", ""),
                            smtp_settings.get("server", ""),
                            smtp_settings.get("port", "")
                        ]
            except Exception:
                pass
        
        # 如果没有配置SMTP信息
        if not smtp_config or not smtp_config[0] or smtp_config[0] == "username":
            self.update_status("请在设置中配置邮箱参数")
            return
            
        username, password, host, port = smtp_config[0], smtp_config[1], smtp_config[2], smtp_config[3]
        
        try:
            smtp = smtplib.SMTP_SSL(host, int(port))
            smtp.login(username, password)
            self.update_status("已登录邮箱")
        except Exception as e:
            self.update_status(f"邮箱登录失败: {e}")
            return

        '''装填内容'''
        msg = MIMEText(html, "html", "UTF-8")
        msg["From"] = username
        msg["To"] = receiver
        msg["Subject"] = title
        self.update_status("邮件内容装填完成")
        
        '''发送邮件'''
        try:
            smtp.sendmail(username, receiver, msg.as_string())
            self.update_status(f"已发送【{title}】至{receiver}")
        except Exception as e:
            self.update_status(f"邮件发送失败: {e}")
        finally:
            smtp.quit()
            self.update_status("成功退出邮箱！")
            
    def run(self):
        """运行UI主循环"""
        self.root.mainloop()


if __name__ == "__main__":
    app = ZhihuHotlistSender()
    app.run()